#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.ComponentModel.Composition;

using octalforty.Componento.ComponentModel.Tracing;
using octalforty.Componento.Shared.SemanticModel;
using octalforty.Componento.Util;

namespace octalforty.Componento.ComponentModel.Installation
{
    /// <summary>
    /// Standard implementation of teh <see cref="IComponentManifestProviderService"/>.
    /// </summary>
    [Export(typeof(IComponentManifestProviderService))]
    public class ComponentManifestProviderService : IComponentManifestProviderService
    {
        #region Public Properties
        /// <summary>
        /// Gets or sets a reference to the collection of <see cref="IComponentManifestProvider"/> objects.
        /// </summary>
        [ImportMany()]
        public Lazy<IComponentManifestProvider>[] ManifestProviders 
        { get; set; }

        /// <summary>
        /// Gets or sets a reference to the <see cref="ITrace"/>.
        /// </summary>
        public ITrace Trace 
        { get; set; }

        public ITraceManagerService TraceManager
        { get; set; }
        #endregion

        [ImportingConstructor()]
        public ComponentManifestProviderService(ITraceManagerService traceManager)
        {
            TraceManager = traceManager;
            Trace = TraceManager.GetTrace(GetType().Name);
        }

        #region IComponentManifestProviderService Members
        /// <summary>
        /// Returns a Component Manifest which identifies Component <paramref name="componentName"/> or <c>null</c>.
        /// </summary>
        /// <param name="componentName"></param>
        /// <param name="uri"></param>
        /// <param name="versionSpecification"></param>
        /// <returns></returns>
        public ComponentManifest GetComponentManifest(string componentName, Uri uri, VersionSpecification versionSpecification)
        {
            if(componentName == null) throw new ArgumentNullException("componentName");
            if(uri == null) throw new ArgumentNullException("uri");
            if(versionSpecification == null) throw new ArgumentNullException("versionSpecification");

            #region Tracing
            Trace.Verbose( "Retrieving Component Manifest for '{0}' from URI '{1}'", componentName, uri);
            #endregion

            var manifest = GetComponentManifestRecursive(componentName, uri, versionSpecification);

            #region Tracing
            if(manifest != null)
                Trace.Verbose( "Retrieved {0} for '{1}' from URI '{2}'", manifest.GetType().Name, componentName, uri);
            else
                Trace.Verbose( "Could not retrieve Component Manifest for '{0}' from URI '{1}'", componentName, uri);
            #endregion

            return manifest;
        }

        /// <summary>
        /// Resolves a <see cref="IComponentManifestProvider"/> capable of providing Component Manifests from
        /// <paramref name="uri"/> or <c>null</c> if no Component Manifest Provider for a given URI is registered.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public IComponentManifestProvider ResolveComponentManifestProvider(Uri uri)
        {
            if(uri == null) throw new ArgumentNullException("uri");

            #region Tracing
            Trace.Verbose( "Resolving Component Manifest Provider for URI '{0}'", uri);
            #endregion

            if(ManifestProviders == null)
            {
                #region Tracing
                Trace.Verbose( "No Component Manifest Providers registered");
                #endregion

                return null;
            } // if

            var componentManifestProvider = InternalResolveComponentManifestProvider(uri);

            #region Tracing
            if(componentManifestProvider != null)
                Trace.Verbose( "Resolved {0} for URI '{1}'", componentManifestProvider.GetType().Name, uri);
            else
                Trace.Verbose( "Could not resolve Component Manifest Provider for URI '{0}'", uri);
            #endregion

            return componentManifestProvider;
        }
        #endregion

        private IComponentManifestProvider InternalResolveComponentManifestProvider(Uri uri)
        {
            foreach(var manifestProvider in ManifestProviders)
                if(manifestProvider.Value.CanProvideManifestFrom(uri))
                    return manifestProvider.Value;

            return null;
        }

        private ComponentManifest GetComponentManifestRecursive(string componentName, Uri uri, VersionSpecification versionSpecification)
        {
            try
            {
                return InternalGetComponentManifestRecursive(componentName, uri, versionSpecification);
            } // try

            catch(ComponentManifestException e)
            {
                throw ExceptionUtil.ComponentManifestException(e,
                    Properties.Resources.CouldNotRetrieveComponentManifestFrom, componentName, uri);
            } // catch
        }

        private ComponentManifest InternalGetComponentManifestRecursive(string componentName, Uri uri, VersionSpecification versionSpecification)
        {
            var manifest = InternalGetComponentManifest(componentName, uri, versionSpecification);
            if(manifest == null)
                return null;

            return manifest.IsMetamanifest ?
                GetComponentManifestRecursive(componentName, manifest.Resources[0].Uri, versionSpecification) :
                manifest;
        }

        private ComponentManifest InternalGetComponentManifest(string componentName, Uri uri, VersionSpecification versionSpecification)
        {
            var componentManifestProvider = ResolveComponentManifestProvider(componentName, uri);
            if(componentManifestProvider == null)
                throw ExceptionUtil.ComponentManifestException(null,
                    Properties.Resources.CouldNotRetrieveComponentManifestFrom, componentName, uri);

            return componentManifestProvider.GetComponentManifest(componentName, uri, versionSpecification);
        }

        private IComponentManifestProvider ResolveComponentManifestProvider(string componentName, Uri uri)
        {
            var componentManifestProvider = ResolveComponentManifestProvider(uri);
            if(componentManifestProvider == null)
                throw ExceptionUtil.ComponentManifestException(null,
                    Properties.Resources.CouldNotResolveComponentManifestProvider, componentName, uri);

            return componentManifestProvider;
        }
    }
}